package com.qeado.content.web;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.qeado.admin.common.BaseConstData;
import com.qeado.common.UploadFileLocation;
import com.qeado.common.helper.AttributeHelper;
import com.qeado.content.model.BaikeInfo;
import com.qeado.content.model.BaikeInfoRef;
import com.qeado.content.service.BaikeInfoServie;

@Controller
public class BaikeInfoController {
	@Autowired
	private BaikeInfoServie baikeInfoService;
	
	@RequestMapping("/baikeInfoManage.ac")
	public String baikeInfoManage(HttpServletRequest request){
		AttributeHelper.removeSessionAttribute(request, "T_");
		List<BaikeInfo> baikeTypeList = baikeInfoService.getBaikeTypeList();
		request.getSession().setAttribute("T_baikeTypeList", baikeTypeList);
		return "content/baike_info_search";
	}
	
	@RequestMapping("/baikeInfoSearch.ac")
	public String baikeInfoSearch(HttpServletRequest request, BaikeInfo baikeInfo){
		List<BaikeInfo> baikeInfoList = baikeInfoService.searchBaikeInfo(baikeInfo);
		request.setAttribute("baikeInfoList", baikeInfoList);
		return "content/baike_info_search";
	}
	
	@RequestMapping("/backToBaikeInfoSearch.ac")
	public String backToBaikeInfoSearch(){
		return "content/baike_info_search";
	}
	
	@RequestMapping("/newBaikeInfo.ac")
	public String newBaikeInfo(){
		return "content/baike_info_manage";
	}
	
	@RequestMapping("/selectBaikeInfo.ac")
	public String selectBaikeInfo(HttpServletRequest request, String id){
		BaikeInfo baikeInfo = baikeInfoService.searchBaikeInfoById(id);
		List<BaikeInfoRef> baikeRefInfoList = baikeInfoService.searchBaikeInfoRefList(id);
		request.setAttribute("baikeInfo", baikeInfo);
		request.setAttribute("baikeRefInfoList", baikeRefInfoList);
		return "content/baike_info_manage";
	}
	
	@RequestMapping("/deleteBaikeInfo.ac")
	public String deleteBaikeInfo(String id){
		baikeInfoService.deleteBaikeInfo(id);
		return "content/baike_info_search";
	}
	
	@RequestMapping("/getBaikePhoto.ac")
	public void getBaikePhoto(HttpServletRequest request, HttpServletResponse response, String fileName) throws UnsupportedEncodingException {
		fileName = URLEncoder.encode(fileName,"UTF-8");
	    response.addHeader("Content-Disposition","attachment;filename=" + fileName);
	    OutputStream output = null;
	    FileInputStream fis = null;
	    try {
	        output = response.getOutputStream();
	        File file = new File(UploadFileLocation.BASE_DIR + "\\baike\\" + fileName);
	        fis = new FileInputStream(file);
	        byte[] b = new byte[1024];
	        int i = 0;
	        while((i = fis.read(b)) > 0) {
	            output.write(b, 0, i);
	        }
	        output.flush();
	    } catch(Exception e) {
	        e.printStackTrace();
	    } finally {
	        if(fis != null) { 
	        	try {
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
	        }
	        if(output != null) {
	        	try {
					output.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
	        }
	    }
	}
	
	@RequestMapping("/saveBaikeInfo.ac")
	public String saveBaikeInfo(HttpServletRequest request, BaikeInfo baikeInfo){
		baikeInfo.setModifier(request.getSession().getAttribute(BaseConstData.USER_ID).toString());
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest)request;
		MultipartFile file = multipartRequest.getFile("localFile");
		if(!file.isEmpty()) {
			String imgName = getFileNameByTime(file.getOriginalFilename());
			try {
				String path = UploadFileLocation.BASE_DIR + "\\baike" ;
				//analyzePath(path);
				if(!"".equals(baikeInfo.getFileName())) {
					File oldFile = new File(path + "\\" + baikeInfo.getFileName());
					oldFile.delete();
				}
				File uploadedFile = new File(path + "\\" + imgName);
				int v;         
				BufferedInputStream inputStream = new BufferedInputStream(file.getInputStream());     
				FileOutputStream outputStream = new FileOutputStream(uploadedFile);     
				byte [] bytes = new byte[1024];     
				while((v = inputStream.read(bytes)) > 0){     
				    outputStream.write(bytes, 0, v);     
				}     
				outputStream.close();     
				inputStream.close();	
			} catch (Exception e) {
				e.printStackTrace();
			}
			baikeInfo.setNewFileName(imgName);
			baikeInfo.setFileName(imgName);
		}
		String message = baikeInfoService.saveBaikeInfo(baikeInfo);
		List<BaikeInfoRef> baikeRefInfoList = baikeInfoService.searchBaikeInfoRefList(baikeInfo.getId());
		request.setAttribute("message", message);
		request.setAttribute("baikeRefInfoList", baikeRefInfoList);
		return "content/baike_info_manage";
	}
	
	@RequestMapping("/selectBaikeRefInfo.ac")
	public ModelAndView selectBaikeRefInfo(String id){
		BaikeInfoRef baikeRefInfo = baikeInfoService.searchBaikeInfoRefById(id);
		return new ModelAndView("content/baike_info_ref", "baikeRefInfo", baikeRefInfo);
	}
	
	@RequestMapping("/saveBaikeRef.ac")
	public String saveBaikeRef(HttpServletRequest request, BaikeInfoRef baikeRefInfo){
		baikeRefInfo.setModifier(request.getSession().getAttribute(BaseConstData.USER_ID).toString());
		baikeInfoService.updateBaikeInfoRef(baikeRefInfo);
		BaikeInfo baikeInfo = baikeInfoService.searchBaikeInfoById(baikeRefInfo.getBaikeId());
		List<BaikeInfoRef> baikeRefInfoList = baikeInfoService.searchBaikeInfoRefList(baikeRefInfo.getBaikeId());
		request.setAttribute("baikeInfo", baikeInfo);
		request.setAttribute("baikeRefInfoList", baikeRefInfoList);
		return "content/baike_info_manage";
	}
	
	@RequestMapping("/deleteBaikeRef.ac")
	public String deleteBaikeRef(HttpServletRequest request, BaikeInfo baikeInfo, String refId){
		baikeInfoService.deleteBaikeRef(refId);
		List<BaikeInfoRef> baikeRefInfoList = baikeInfoService.searchBaikeInfoRefList(baikeInfo.getId());
		request.setAttribute("baikeRefInfoList", baikeRefInfoList);
		return "content/baike_info_manage";
	}
	
	@RequestMapping("/backToBaikeInfo.ac")
	public String backToBaikeInfo(HttpServletRequest request, BaikeInfoRef baikeRefInfo){
		BaikeInfo baikeInfo = baikeInfoService.searchBaikeInfoById(baikeRefInfo.getBaikeId());
		List<BaikeInfoRef> baikeRefInfoList = baikeInfoService.searchBaikeInfoRefList(baikeRefInfo.getBaikeId());
		request.setAttribute("baikeInfo", baikeInfo);
		request.setAttribute("baikeRefInfoList", baikeRefInfoList);
		return "content/baike_info_manage";
	}
	
	private synchronized String getFileNameByTime(String input){
        int index = input.lastIndexOf(".");
        return System.currentTimeMillis() + input.substring(index);
    }
	
	private synchronized boolean mkdir(String path) {   
        File file = new File(path); 
        if(file.exists()){ 
        	return false; 
        } else { 
        	file.mkdir(); 
        	return true;
        } 			
	}

	private void analyzePath(String path) {
		String[] paths = path.split("/");
		path = paths[0];
		for(int i=1; i<paths.length; i++) {
			path = path + "\\" +paths[i];
			mkdir(path);
			System.out.println(path);
		}
	}
}
